package org.kl.bf.web.basic;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletRequest;

import org.kl.bf.entity.basic.User;
import org.kl.bf.service.basic.UserService;
import org.kl.bf.utils.EmailUtil;
import org.kl.bf.utils.MD5Util;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/basic/validate")
public class EmailValidateController extends BasicController {

	@Autowired
	private UserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public String validateEmail() {
		return "basic/emailBindingList";
	}

	/**
	 * 保存邮箱
	 */
	@RequestMapping(value = "updateEmail")
	public String updateEmail(@RequestParam(value = "email") String email, Model model, RedirectAttributes redirectAttributes,
			ServletRequest request) {
		Random random = new Random();
		int randomCode = random.nextInt(1000000);
		while (randomCode <= 100000) {
			randomCode = random.nextInt(1000000);
		}
		String validateCode = MD5Util.mD5Encode(randomCode + "");

		Timestamp validateTime = new Timestamp(new Date().getTime());
		Timestamp overdueTime = new Timestamp(validateTime.getTime() + 86400000);

		User user = userService.getUser(BasicController.getCurrentUserId());
		user.setEmail(email);
		user.setStatus(0);
		user.setValidateCode(validateCode);
		user.setValidateTime(validateTime);
		user.setOverdueTime(overdueTime);
		userService.saveUser(user);

		model.addAttribute("email", email);

		Map<String, Object> emailMap = new HashMap<String, Object>();
		emailMap.put("qq.com", "http://mail.qq.com/");
		emailMap.put("163.com", "http://email.163.com/");
		emailMap.put("126.com", "http://email.126.com/");
		emailMap.put("21cn.com", "http://mail.21cn.com/");
		emailMap.put("sina.com.cn", "http://mail.sina.com.cn/");
		emailMap.put("sohu.com", "http://mail.sohu.com/");

		String key = email.split("@")[1];
		model.addAttribute("http", emailMap.get(key).toString());

		sendEmail(email, validateCode);
		return "basic/emailBindingSuccessList";
	}

	/**
	 * 检验邮箱是否已被绑定
	 */
	@RequestMapping(value = "checkEmail", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String checkEmail(@RequestParam("email") String email) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("EQ_email", email);
		List<User> list = userService.searchAll(searchParams);
		if (list.size() > 0) {
			if (list.get(0).getId().equals(getCurrentUserId())) {
				return ajaxMsg("邮箱已被绑定", true, null);
			}
		}
		return ajaxMsg("", false, null);
	}

	// 链接有问题，待修复
	private void sendEmail(String email, String validateCode) {

		StringBuffer sb = new StringBuffer("请点击链接激活邮箱：");
		sb.append("<a href=\"http://localhost:9089/WisdomSchool/basic/validate/validateEmail?path=,");
		sb.append(email);
		sb.append(",");
		sb.append(validateCode);
		sb.append("\">http://localhost:9089/WisdomSchool/basic/validate/validateEmail?email=");
		sb.append(email);
		sb.append("&validateCode=");
		sb.append(validateCode);
		sb.append("</a></br>");
		sb.append("(该链接在24小时内有效，24小时后需要重新获取)");
		EmailUtil.send(email, sb.toString(), 0);
	}

	/**
	 * 激活邮箱
	 */
	@RequestMapping(value = "validateEmail")
	public String validateEmail(@RequestParam(value = "path") String path, Model model, RedirectAttributes redirectAttributes, ServletRequest request) {
		String email = path.split(",")[1];
		String validateCode = path.split(",")[2];
		User user = userService.findUserByEmail(email);
		// 验证用户是否存在
		if (user != null) {
			// 验证用户激活状态
			if (user.getStatus() == 0) {
				// /没激活
				Timestamp currentTime = new Timestamp(new Date().getTime());// 获取当前时间
				// 验证链接是否过期
				if (currentTime.before(user.getOverdueTime())) {
					// 验证激活码是否正确
					if (validateCode.equals(user.getValidateCode())) {
						// 激活成功， 并更新用户的激活状态，为已激活
						user.setStatus(1);// 把状态改为激活
						userService.saveUser(user);
						model.addAttribute("message", "恭喜您，邮箱" + email + "激活成功！");
						model.addAttribute("success", true);
					} else {
						model.addAttribute("message", "激活码不正确！");
						model.addAttribute("success", false);
					}
				} else {
					model.addAttribute("message", "激活链接已失效！");
					model.addAttribute("success", false);
				}
			} else {
				model.addAttribute("message", "邮箱已激活，无需重新激活！");
				model.addAttribute("success", false);
			}
		} else {
			model.addAttribute("message", "该邮箱还未绑定（邮箱地址不存在）！");
			model.addAttribute("success", false);
		}
		return "basic/emailValidateInfoList";
	}

}
